package com.dating.activity;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.dating.entities.Her;
import com.dating.libs.web.services.datingservice.DatingService;
import com.dating.libs.web.services.datingservice.MatchingUser;
import com.dating.libs.web.services.datingservice.UserProperties;
import com.dating.pref.Function;
import com.dating.view.RowCompareYouHer;

public class Matching extends Activity implements OnClickListener {
	TextView name, age, address, distance, her, percentMatching, more;
	ProgressBar pgPercentMatching, pgTitle;
	ImageView mAvatar;
	Button btnDetail, btnChat, btnInterest;
	LinearLayout layoutMatchingContent;

	Handler mHandler;
	Bitmap mBmp = null;
	MatchingUser _mcUser = null;
	ArrayList<UserProperties> herProperties=null;
	
	int userID=82;
	Her girl=new Her(0);
	
	Boolean loading1=true,loading2=true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		Bundle bundle=getIntent().getExtras();
		
		setContentView(R.layout.matching);

		mHandler = new Handler();
		
		findById();
		
		setOnListener();

		try{
			int id=Integer.valueOf(bundle.getString("id_her"));
			if(id>-1){
				userID=id;
				girl._id_username=id+"";
				Log.e("id her", id+"");
				getMatching();
			}else
				finish();
		}catch(NullPointerException e){
			Log.e("can not get id Her", e.toString());
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	public void getMatching(){
		if(loading1 && loading2){
			if(girl._id_username!=null && girl._id_username!=""){
				Toast.makeText(this, "get best matching", Toast.LENGTH_SHORT).show();
				getBestMatching();
			}else{
				Toast.makeText(this, "get matching:"+girl._id_username, Toast.LENGTH_SHORT).show();
				getBestMatching(girl._id_username);
			}
			getAvatar();
		}
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	private void getAvatar() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						pgTitle.setVisibility(View.VISIBLE);
					}
				});
				DatingService dt = new DatingService();
				URL url;
				try {
					url = new URL(
							"http://anh.24h.com.vn/upload/1-2011/images/2011-02-22/1298362370-CHUNG-HAN-DONG--3-.jpg");
					mBmp = Function.getBitmapFromUrl(url);
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							mAvatar.setImageBitmap(mBmp);
							loading2=false;
						}
					});
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (NullPointerException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							pgTitle.setVisibility(View.INVISIBLE);
						}
					});
				}
			}
		}).start();
	}

	public void getBestMatching(String herID){
		// get Matching her
	}
	
	private void getBestMatching() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						pgTitle.setVisibility(View.VISIBLE);
					}
				});
				_mcUser = null;
				DatingService dt = new DatingService();
				try {
					Log.e("internet", "load matching");
					// get matching
					_mcUser = dt.getBestMatching();
					// get user properties
					herProperties = dt.getAllUserProperties(_mcUser.getUserID(0));
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							updateMatchingUser(layoutMatchingContent, _mcUser,herProperties);
							loading1=false;
							
							
						}
					});
					
					
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					mHandler.post(new Runnable() {

						@Override
						public void run() {
							pgTitle.setVisibility(View.INVISIBLE);
						}
					});
				}
			}
		}).start();
	}

	private void findById() {
		her = (TextView) findViewById(R.id.tv_her);
		more = (TextView) findViewById(R.id.tv_more);
		age = (TextView) findViewById(R.id.matching_age);
		name = (TextView) findViewById(R.id.matching_name);
		address = (TextView) findViewById(R.id.matching_address);
		distance = (TextView) findViewById(R.id.matching_distance);
		percentMatching = (TextView) findViewById(R.id.tv_percent_matching);

		mAvatar = (ImageView) findViewById(R.id.im_avatar);

		pgPercentMatching = (ProgressBar) findViewById(R.id.pg_matching);
		pgTitle = (ProgressBar) findViewById(R.id.head_progressbar);

		layoutMatchingContent = (LinearLayout) findViewById(R.id.layout_matching_content);

		btnChat = (Button) findViewById(R.id.btn_chat);
		btnDetail = (Button) findViewById(R.id.btn_detail);
		btnInterest = (Button) findViewById(R.id.btn_interest);
	}

	private void setOnListener() {
		btnChat.setOnClickListener(_listener);
		btnDetail.setOnClickListener(_listener);
		btnInterest.setOnClickListener(_listener);
		mAvatar.setOnClickListener(this);
	}

	void btnClicked(View v) {
		switch (v.getId()) {
		case R.id.btn_detail:
			
			break;
		case R.id.btn_chat:
			if(userID>-1){
				Intent i=new Intent(this, Chat.class);
				Bundle b=new Bundle();
				b.putInt("user_id", userID);
				Log.v("id user", userID+"");
				i.putExtras(b);
				startActivity(i);
			}else{
				Toast.makeText(this, userID+"", Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}
	}

	private void updateMatchingUser(LinearLayout layoutContent,
			MatchingUser matchingUser,ArrayList<UserProperties> herProperties) {
		layoutContent.removeAllViews();

		for (UserProperties _t : matchingUser.getMatchingProperties()) {
			for (UserProperties _m : Dating.ME.mMeProperties) {
				if (_t.getName("").toLowerCase()
						.equals(_m.getName("").toLowerCase())) {
					RowCompareYouHer _r = new RowCompareYouHer(this,_m.getValue(""), _t.getValue(""),_m.getName(""));
					layoutContent.addView(_r);
					break;
				}
			}
		}
		pgPercentMatching.setMax(100);
		pgPercentMatching.setProgress(matchingUser.getResult(0));

		percentMatching.setText(matchingUser.getResult(0) + "% match");
		
		// User infomation
		if (herProperties!=null && herProperties.size() > 0) {
			for(UserProperties _i: herProperties){
				if(_i.getName("").toLowerCase().equals(new String("Age").toLowerCase()))
					age.setText(_i.getValue(""));
				if(_i.getName("").toLowerCase().equals(new String("Adress").toLowerCase()))
					address.setText(_i.getValue(""));
			}
		}
	}

	View.OnClickListener _listener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			btnClicked(v);
		}
	};

	protected void onSaveInstanceState(Bundle outState) {
		if (mBmp != null)
			outState.putBoolean("saved", true);
		outState.putBoolean("loading1", loading1);
		outState.putBoolean("loading2", loading2);
		outState.putParcelable("avatar", mBmp);
		outState.putSerializable("matchingUser", _mcUser);
		outState.putSerializable("herproperties", herProperties);
		
		outState.putString("name", name.getText().toString());
		outState.putString("age",age.getText().toString());
		outState.putString("address",address.getText().toString());
		outState.putString("distance",distance.getText().toString());
	};

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if(savedInstanceState.containsKey("saved")){
			loading1=savedInstanceState.getBoolean("loading1");
			loading2=savedInstanceState.getBoolean("loading2");
			try {
				mBmp = savedInstanceState.getParcelable("avatar");
				mAvatar.setImageBitmap(mBmp);
				if (mBmp == null)
					Log.e("bmp", "null");
			} catch (NullPointerException e) {
				e.printStackTrace();
				mAvatar.setImageResource(R.drawable.noavatar);
			} catch (Exception e) {
				e.printStackTrace();
				mAvatar.setImageResource(R.drawable.noavatar);
			}
	
			try {
				_mcUser = (MatchingUser) savedInstanceState
						.getSerializable("matchingUser");
				
				updateMatchingUser(layoutMatchingContent, _mcUser,herProperties);
			} catch (NullPointerException e) {
				e.printStackTrace();
				mAvatar.setImageResource(R.drawable.noavatar);
			} catch (Exception e) {
				e.printStackTrace();
				mAvatar.setImageResource(R.drawable.noavatar);
			}
			// TextView
			name.setText(savedInstanceState.getString("name"));
			age.setText(savedInstanceState.getString("age"));
			address.setText(savedInstanceState.getString("address"));
			distance.setText(savedInstanceState.getString("distance"));
		}else{
			loading1=true;
			loading2=false;
		}
	}

	@Override
	public void onClick(View v) {
		if(v.getId()==mAvatar.getId()){
			Intent i=new Intent(this, ShowImage.class);
			Bundle b=new Bundle();
			b.putString("user_id", girl._id_username);
			i.putExtras(b);
			startActivity(i);
		}
	}
}
